package com.chouren.goandroid.img;

import java.io.File;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileCacheManager {
	public static String getExternalCacheDir(Context context) {
		String result = null;
		if(hasSDCard()) {
			File externalCacheDir = context.getExternalCacheDir();
			if(externalCacheDir != null) {
				result = context.getExternalCacheDir().getAbsolutePath() + "/img";
				new File(result).mkdirs();
			}else {
				throw new Error("get external cache directory is null, "
						+ "possible caused by you application do not has WRITE_EXTERNAL permission");
			}
			
		}
		return result;
	}
	
	public static String getCacheDir(Context context) {
		String cacheDir = context.getCacheDir().getAbsolutePath() + "/img";
		File file = new File(cacheDir);
		if(!file.exists()) file.mkdirs(); 
		return cacheDir;
	}
	
	private static boolean hasSDCard() {
		String status = Environment.getExternalStorageState();
		if (!status.equals(Environment.MEDIA_MOUNTED)) {
			return false;
		} 
		return true;
	}
	
	public static boolean deleteDirectory(String filePath) {
		if (null == filePath) {
			Log.e("FileCacheManager", "the parameter filePath is null, cancel delete");
			return false;
		}

		File file = new File(filePath);

		if (file == null || !file.exists()) {
			Log.e("FileCacheManager", "the parameter filePath is not a file or dir, cancel delete");
			return false;
		}

		if (file.isDirectory()) {
			File[] list = file.listFiles();

			for (int i = 0; i < list.length; i++) {
				if (list[i].isDirectory()) {
					deleteDirectory(list[i].getAbsolutePath());
				} else {
					list[i].delete();
				}
			}
		}

		file.delete();
		return true;
	}
}
